package com.lin.server.ws;


import com.lin.entity.PlaneData;
import com.lin.entity.key.WsDataMapKey;
import com.lin.entity.vo.PlaneWsVo;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * ws公共数据保存器
 */
@Component
@Data
public class WsDataHolder {
    // 每隔BATCH_COUNT条存数据库，然后清理list，方便内存回收
    public static final int BATCH_COUNT = 5;

    // 缓存飞机数据（zh）
    private List<PlaneData> planeDataList = new ArrayList<>(BATCH_COUNT);

    // 历史飞机信息
    private Map<String, PlaneWsVo> historyPlanes;

    // 定时任务 <taskName,task>
    private Map<WsDataMapKey, ScheduledFuture<?>> scheduleTasks = new HashMap<>();

    // 线程任务 <taskName,Runnable>
    private Map<WsDataMapKey, Runnable> threadTasks = new HashMap<>();

    // 航迹回放数据缓存
    private List<PlaneData> tracePlaybackCache;
    Set<PlaneData> uniquePlaneSet = new HashSet<>();
    public void setTracePlaybackCache(List<PlaneData> tracePlaybackCache) {
        this.tracePlaybackCache = new ArrayList<>();
        this.tracePlaybackCache.addAll(tracePlaybackCache);
        // 过滤相同点
        this.tracePlaybackCache = this.tracePlaybackCache.stream().filter(uniquePlaneSet::add).collect(Collectors.toList());
        this.tracePlaybackCache.sort(Comparator.comparing(PlaneData::getTarTime));
        uniquePlaneSet.clear();
    }

    /**
     * 补充航迹回放数据缓存
     *
     * @param tracePlaybackCache
     */
    public void addTracePlaybackCache(List<PlaneData> tracePlaybackCache) {
        this.tracePlaybackCache.addAll(tracePlaybackCache);
        this.tracePlaybackCache = this.tracePlaybackCache.stream().filter(uniquePlaneSet::add).collect(Collectors.toList());
        this.tracePlaybackCache.sort(Comparator.comparing(PlaneData::getTarTime));
        uniquePlaneSet.clear();
    }

    public void addTask(WsDataMapKey dataMapKey, ScheduledFuture<?> task, Runnable threadTask) {
        this.scheduleTasks.put(dataMapKey, task);
        this.threadTasks.put(dataMapKey, threadTask);
    }

    public void removeTask(WsDataMapKey wsDataMapKey) {
        this.scheduleTasks.remove(wsDataMapKey);
        this.threadTasks.remove(wsDataMapKey);
    }

    /**
     * 获取定时任务
     *
     * @param dataMapKey
     * @return
     */
    public ScheduledFuture<?> getScheduleTask(WsDataMapKey dataMapKey) {
        return this.scheduleTasks.get(dataMapKey);
    }

    /**
     * 获取线程任务
     *
     * @param dataMapKey
     * @return
     */
    public Runnable getThreadTask(WsDataMapKey dataMapKey) {
        return this.threadTasks.get(dataMapKey);
    }
}
